package com.hyfrogx.modules.manage.service.chargePayRecord.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.param.Constants;
import com.hyfrogx.common.param.PayType;
import com.hyfrogx.common.utils.Constant;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.Terminal;
import com.hyfrogx.config.AliPayConfig;
import com.hyfrogx.modules.app.entity.HyUserAttentionEntity;
import com.hyfrogx.modules.app.form.ios.IosForm;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.ChargePayRecordConstant;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.FrogxTaskCode;
import com.hyfrogx.modules.app.utils.IosVerifyUtil;
import com.hyfrogx.modules.manage.dao.chargePayRecordDao.ChargePayRecordDao;
import com.hyfrogx.modules.manage.entity.HyProductionScaleEntity;
import com.hyfrogx.modules.manage.entity.chargePayRecord.ChargePayRecordEntity;
import com.hyfrogx.modules.manage.entity.payrecord.HyPayRecord;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.manage.service.HyProductionVacuateService;
import com.hyfrogx.modules.manage.service.chargePayRecord.ChargePayRecordService;
import com.hyfrogx.modules.manage.service.task.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Wrapper;
import java.util.*;

/**
 * @Author: Luo
 * @Date: 2019/12/5 17:49
 */
@Service
public class ChargePayRecordServiceImpl extends ServiceImpl<ChargePayRecordDao, ChargePayRecordEntity> implements ChargePayRecordService {

    Logger logger = LoggerFactory.getLogger("alipay_coin");

    Logger loggerios = LoggerFactory.getLogger("pay");

    @Autowired
    AliPayConfig aliPayConfig;

    @Autowired
    HyPayRecordService payRecordService;

    @Autowired
    UserService userService;

    @Autowired
    TaskService taskService;
    @Autowired
    private HyProductionVacuateService hyProductionVacuateService;




    @Override
    public String notify(HttpServletRequest request, HttpServletResponse response) {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
            logger.info("支付宝回调之后的参数列表:" + params);
        }
        logger.info("回调参数" + params.toString());
        //商品订单号
        String out_trade_no = request.getParameter("out_trade_no");            // 商户订单号
        // 当前交易状态
        String tradeStatus = request.getParameter("trade_status");            //交易状态
        // 支付时间
        String payDate = request.getParameter("gmt_payment");            //交易状态
        // 实收金额
        String receipt_amount = request.getParameter("receipt_amount");
        //实付金额
        String buyer_pay_amount = request.getParameter("buyer_pay_amount");
        boolean signVerified = false;
        try {
            //3.1调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getPublic_key(), FrogConstant.CharSet.utf8,  "RSA2");
            if(signVerified){
                if(tradeStatus.equals(ChargePayRecordConstant.AliPayStatus.success)){
                    //存入支付订单表中
                    ChargePayRecordEntity payRecordEntity = new ChargePayRecordEntity();
                    payRecordEntity.setOutTradeNo(out_trade_no);
                    payRecordEntity.setStatus(ChargePayRecordConstant.PayStatus.PAY_OK);
                    payRecordEntity.setBuyerPayAmount(new BigDecimal(buyer_pay_amount));
                    payRecordEntity.setReceiptAmount(new BigDecimal(receipt_amount));
                    boolean update = this.update(new QueryWrapper<ChargePayRecordEntity>()
                            .eq("out_trade_no", out_trade_no).ne("status", 1));
                    if(!update){
                        return "流水号错误";
                    }
                    this.upDateByOutTradeNo(payRecordEntity);
                    return "success";
                }
            }else {
                logger.info(out_trade_no + "验签失败");
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }catch (Exception e){
            return e.getMessage();
        }
        return "failure";
    }

    @Override
    public void upDateByOutTradeNo(ChargePayRecordEntity payRecordEntity) throws Exception{
        //更新订单
        boolean update = this.update(new QueryWrapper<ChargePayRecordEntity>()
                .eq("out_trade_no", payRecordEntity.getOutTradeNo()).ne("status", 1));
        if(!update){
            logger.info("alipay update fail" + payRecordEntity.getOutTradeNo());
            return;
        }
        //充值成功
        logger.info("alipay record success" + payRecordEntity.getOutTradeNo());
        if(payRecordEntity.getStatus().equals(ChargePayRecordConstant.PayStatus.PAY_OK)){
            ChargePayRecordEntity chargePayRecordEntity = this.getOne(new QueryWrapper<ChargePayRecordEntity>()
                    .eq("out_trade_no", payRecordEntity.getOutTradeNo()));
            chargePayRecordEntity.setCoin(chargePayRecordEntity.getCoin()+chargePayRecordEntity.getChargePresentCoin());
            //存入支付账单
            if(chargePayRecordEntity!=null){
                HyPayRecord record = new HyPayRecord();
                record.setTotal(chargePayRecordEntity.getCoin());
                record.setMoney(chargePayRecordEntity.getTotalAmount());
                record.setNum(chargePayRecordEntity.getTotalAmount());
                record.setType(PayType.charge.getCode());
                record.setYid(chargePayRecordEntity.getUid());
                record.setUid(FrogConstant.admin_uid);
                payRecordService.save(record);
                //充值成功后给用户增加蛙豆
                userService.addBean(chargePayRecordEntity.getUid(),chargePayRecordEntity.getCoin());
                taskService.recharegTask(chargePayRecordEntity.getUid(), new BigDecimal(chargePayRecordEntity.getTotalAmount())
                        .setScale(2, BigDecimal.ROUND_HALF_UP) , FrogxTaskCode.TaskCode.ACTIVITY_RECHAREG);
                logger.info(chargePayRecordEntity.getOutTradeNo() + "*****coin add success");
            }
        }
    }


    @Override
    public Boolean iosCharge(IosForm form) throws Exception {
        loggerios.info("ios:" + form.getUid() + "*receipt-data:" + form.getData());
        String verify = IosVerifyUtil.buyAppVerify(form.getData(), FrogConstant.iosUrl.urlVerify);
        if(StrUtil.isBlank(verify)){
           throw new Exception("我丢失了回调");
        }
        JSONObject jsonObject = JSONObject.parseObject(verify);
        String states = jsonObject.getString("status");
        //是沙盒环境，应沙盒测试，否则执行下面
        if("21007".equals(states)){
            //2.再沙盒测试  发送平台验证
            verify = IosVerifyUtil.buyAppVerify(form.getData(), 0);
            logger.info("沙盒环境，苹果平台返回JSON:" + verify);
            jsonObject = JSONObject.parseObject(verify);
            states = jsonObject.getString("status");
        }
        // 前端所提供的收据是有效的    验证成功
        if("0".equals(states)){
            String receipt = jsonObject.getString("receipt");
            JSONObject receiptObject = JSONObject.parseObject(receipt);
            String inApp = receiptObject.getJSONArray("in_app").toString();
            System.out.println("inApp"+inApp);
            JSONObject in_appJson = JSONObject.parseObject(inApp.substring(1, inApp.length() - 1));
            System.out.println("in_appJson"+in_appJson.toJSONString());


            String ss = in_appJson.getString("product_id");
            String str = ss.substring(ss.indexOf("_")+1,ss.length());
            Integer product_id = Integer.parseInt(str);
            String transaction_id = in_appJson.getString("transaction_id");   // 订单号
            ChargePayRecordEntity chargePayRecord = new ChargePayRecordEntity();
            chargePayRecord.setUid(form.getUid());
            chargePayRecord.setOutTradeNo(transaction_id);
            if(StrUtil.isBlank(transaction_id)){
                return false;
            }
            int count = this.count(new QueryWrapper<ChargePayRecordEntity>()
                    .eq("out_trade_no", transaction_id));
            if(count>0){
                return false;
            }
            //查询充值比例
            HyProductionScaleEntity scaleEntity = hyProductionVacuateService.getOne(new QueryWrapper<HyProductionScaleEntity>()
                    .eq("param_key", FrogConstant.SysConfigKey.IOS_CHARGE_SCALE));
            chargePayRecord.setTotalAmount(product_id);
            chargePayRecord.setCoin( product_id*scaleEntity.getScale());
            //chargePayRecord.setType(form.getType());
            chargePayRecord.setUpdateDate(new Date());
            chargePayRecord.setReceiptAmount(new BigDecimal(product_id));
            chargePayRecord.setBuyerPayAmount(new BigDecimal(product_id));
            chargePayRecord.setChargePresentCoin(0);
            chargePayRecord.setTerminal(Terminal.DisplayChannel.ios);
            chargePayRecord.setChannel(Constants.PayChannel.APPLE);
            if ((int)jsonObject.get("status") == 0){
                chargePayRecord.setStatus(Constants.PayStatus.SUCCESS);
                HyPayRecord payRecord = new HyPayRecord();
                payRecord.setCreatedate(new Date());
                payRecord.setMoney(product_id);
                payRecord.setNum(0);
                // 计入了活动赠送
                int sum = chargePayRecord.getCoin() + chargePayRecord.getChargePresentCoin();
                payRecord.setTotal(sum);
                payRecord.setType(PayType.charge.getCode());
                payRecord.setUid(FrogConstant.admin_uid);
                payRecord.setYid(form.getUid());
                this.save(chargePayRecord);
                userService.addBean(form.getUid(), sum);
                payRecordService.save(payRecord);
                BigDecimal bigDecimal = new BigDecimal(0.7);
                System.out.println("ios充值任务启动");
                System.out.println("充值实际到账为---" + new BigDecimal(String.valueOf(chargePayRecord.getReceiptAmount().multiply(bigDecimal))).setScale(2, BigDecimal.ROUND_HALF_UP));
                //先注释掉活动任务充值的情况
//                try {
//                    taskService.recharegTask(form.getUid(), new BigDecimal(
//                            String.valueOf(chargePayRecord.getReceiptAmount().multiply(bigDecimal))).setScale(2, BigDecimal.ROUND_HALF_UP), Constants.TaskCode.ACTIVITY_RECHAREG);
//               }catch (Exception e){
//                    throw new Exception(e.getMessage());
//                }
                System.out.println("ios充值完成 蛙豆："+sum);
                logger.info("ios:charge:buy:"+chargePayRecord.getOutTradeNo()+"success:" + form.getUid());
                return true;
            }else{
                chargePayRecord.setStatus(Constants.PayStatus.CREATE);
                this.save(chargePayRecord);
                return false;
            }
        }
        return null;
    }

    @Override
    public void cancleOrderById(Integer id) throws ServiceException {
        ChargePayRecordEntity chargePayRecordEntity = this.baseMapper.selectById(id);
    }

    @Override
    public Page getPayRecordList(QueryExt queryExt) {
        Map map = new HashMap(16);
        map.putAll(queryExt.getCondition());
        List<Map> result =this.baseMapper.getPayRecordList(queryExt,map);
        queryExt.setRecords(result);
        return queryExt;
    }

    @Override
    public Page findByPage(QueryExt queryExt) {
        Map map = new HashMap();
        map.putAll(queryExt.getCondition());
        List<ChargePayRecordEntity> result =this.baseMapper.findByPage(queryExt,map);
        for (ChargePayRecordEntity record : result){
           // record.setVip(userVipService.getUserVipByUid(record.getUid()));
            // 如果是苹果内购，修改收款金额应为支付金额的70%,并且取两位小数向上取整：https://blog.csdn.net/qq_36497605/article/details/70597318
            if(record.getChannel().equals(Constants.PayChannel.APPLE)){
                BigDecimal   b   =   record.getReceiptAmount().multiply(new BigDecimal(0.7));
                float   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).floatValue();
                BigDecimal ff = new BigDecimal(f1);
                record.setReceiptAmount(ff);
            }
        }
        queryExt.setRecords(result);
        return queryExt;

    }


}
